package com.example.service.impl;

import com.example.common.Result;
import com.example.entity.AdminReports;
import com.example.mapper.AdminReportsMapper;
import com.example.mapper.ConsumptionRecordMapper;
import com.example.mapper.PurchaseRecordMapper;
import com.example.mapper.RechargeRecordMapper;
import com.example.service.AdminReportsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 管理员报表服务实现类
 */
@Slf4j
@Service
public class AdminReportsServiceImpl implements AdminReportsService {
    
    @Autowired
    private ConsumptionRecordMapper consumptionRecordMapper;
    
    @Autowired
    private PurchaseRecordMapper purchaseRecordMapper;
    
    @Autowired
    private RechargeRecordMapper rechargeRecordMapper;
    
    @Autowired
    private AdminReportsMapper adminReportsMapper;
    
    @Override
    public Result<Map<String, Object>> getAdminReportsData(String startDate, String endDate, String timeType) {
        try {
            Map<String, Object> result = new HashMap<>();
            
            // 获取全平台统计数据
            Map<String, Object> statistics = getPlatformStatisticsData(startDate, endDate);
            result.put("statistics", statistics);
            
            // 获取收入趋势数据
            Map<String, Object> revenueData = getPlatformRevenueData(startDate, endDate, timeType);
            result.put("revenueData", revenueData);
            
            // 获取成本分析数据
            Map<String, Object> costData = getCostAnalysisData(startDate, endDate);
            result.put("costData", costData);
            
            // 获取利润分析数据
            Map<String, Object> profitData = getProfitAnalysisData(startDate, endDate);
            result.put("profitData", profitData);
            

            
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取管理员报表数据失败", e);
            return Result.error("获取管理员报表数据失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result<Map<String, Object>> getPlatformIncomeStatistics(String startDate, String endDate) {
        try {
            Map<String, Object> statistics = getPlatformStatisticsData(startDate, endDate);
            return Result.success(statistics);
        } catch (Exception e) {
            log.error("获取平台收入统计失败", e);
            return Result.error("获取平台收入统计失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result<Map<String, Object>> getPlatformRevenueTrend(String startDate, String endDate, String timeType) {
        try {
            Map<String, Object> revenueData = getPlatformRevenueData(startDate, endDate, timeType);
            return Result.success(revenueData);
        } catch (Exception e) {
            log.error("获取平台收入趋势失败", e);
            return Result.error("获取平台收入趋势失败：" + e.getMessage());
        }
    }
    

    
    @Override
    public Result<Map<String, Object>> getCostAnalysis(String startDate, String endDate) {
        try {
            Map<String, Object> costData = getCostAnalysisData(startDate, endDate);
            return Result.success(costData);
        } catch (Exception e) {
            log.error("获取成本分析失败", e);
            return Result.error("获取成本分析失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result<Map<String, Object>> getProfitAnalysis(String startDate, String endDate) {
        try {
            Map<String, Object> profitData = getProfitAnalysisData(startDate, endDate);
            return Result.success(profitData);
        } catch (Exception e) {
            log.error("获取利润分析失败", e);
            return Result.error("获取利润分析失败：" + e.getMessage());
        }
    }
    
    // 测试方法实现
    @Override
    public BigDecimal testTodayPackageRevenue() {
        try {
            return consumptionRecordMapper.selectTodayTotalConsume();
        } catch (Exception e) {
            log.error("测试今日套餐收入失败", e);
            return BigDecimal.ZERO;
        }
    }
    
    @Override
    public BigDecimal testTodayPurchaseRevenue() {
        try {
            return purchaseRecordMapper.selectTodayTotalPurchaseIncome();
        } catch (Exception e) {
            log.error("测试今日购买收入失败", e);
            return BigDecimal.ZERO;
        }
    }
    
    @Override
    public BigDecimal testTodayRechargeRevenue() {
        try {
            return rechargeRecordMapper.selectTodayTotalRecharge();
        } catch (Exception e) {
            log.error("测试今日充值收入失败", e);
            return BigDecimal.ZERO;
        }
    }
    
    /**
     * 获取全平台统计数据（包含成本和利润）
     */
    private Map<String, Object> getPlatformStatisticsData(String startDate, String endDate) {
        Map<String, Object> statistics = new HashMap<>();
        
        try {
            log.info("开始获取平台统计数据，参数：startDate={}, endDate={}", startDate, endDate);
            
            // 1. 套餐收入统计（全平台，不按店长分组）
            BigDecimal packageRevenue;
            if (startDate != null && endDate != null) {
                packageRevenue = consumptionRecordMapper.selectTotalConsumeByDateRange(startDate + " 00:00:00", endDate + " 23:59:59");
            } else {
                packageRevenue = consumptionRecordMapper.selectTodayTotalConsume();
            }
            log.info("套餐收入查询结果：{}", packageRevenue);
            
            // 2. 购物收入统计（全平台，不按店长分组）
            BigDecimal purchaseRevenue;
            if (startDate != null && endDate != null) {
                purchaseRevenue = purchaseRecordMapper.selectTotalPurchaseIncomeByDateRange(startDate + " 00:00:00", endDate + " 23:59:59");
            } else {
                purchaseRevenue = purchaseRecordMapper.selectTodayTotalPurchaseIncome();
            }
            log.info("购物收入查询结果：{}", purchaseRevenue);
            
            // 3. 充值收入统计（全平台）
            BigDecimal rechargeRevenue;
            if (startDate != null && endDate != null) {
                rechargeRevenue = rechargeRecordMapper.selectTotalRechargeByDateRange(startDate + " 00:00:00", endDate + " 23:59:59");
            } else {
                rechargeRevenue = rechargeRecordMapper.selectTodayTotalRecharge();
            }
            log.info("充值收入查询结果：{}", rechargeRevenue);
            
            // 4. 计算总收入
            BigDecimal totalRevenue = (packageRevenue != null ? packageRevenue : BigDecimal.ZERO)
                    .add(purchaseRevenue != null ? purchaseRevenue : BigDecimal.ZERO)
                    .add(rechargeRevenue != null ? rechargeRevenue : BigDecimal.ZERO);
            log.info("总收入计算结果：{}", totalRevenue);
            
            // 5. 计算总成本
            // 套餐服务成本（主要是人工成本，假设为套餐收入的20%）
            BigDecimal packageCost = (packageRevenue != null ? packageRevenue : BigDecimal.ZERO)
                    .multiply(new BigDecimal("0.20"));
            
            // 购物成本（假设为购物收入的60%）
            BigDecimal purchaseCost = (purchaseRevenue != null ? purchaseRevenue : BigDecimal.ZERO)
                    .multiply(new BigDecimal("0.60"));
            
            // 充值成本（充值业务成本很低，假设为充值收入的2%，主要是手续费等）
            BigDecimal rechargeCost = (rechargeRevenue != null ? rechargeRevenue : BigDecimal.ZERO)
                    .multiply(new BigDecimal("0.02"));
            
            BigDecimal totalCost = packageCost.add(purchaseCost).add(rechargeCost);
            
            // 6. 计算总利润
            BigDecimal totalProfit = totalRevenue.subtract(totalCost);
            
            // 7. 计算利润率
            BigDecimal profitMargin = BigDecimal.ZERO;
            if (totalRevenue.compareTo(BigDecimal.ZERO) > 0) {
                profitMargin = totalProfit.divide(totalRevenue, 4, RoundingMode.HALF_UP).multiply(new BigDecimal("100"));
            }
            
            // 8. 统计订单数量
            long totalOrders;
            if (startDate != null && endDate != null) {
                totalOrders = consumptionRecordMapper.selectTotalCountByDateRange(startDate + " 00:00:00", endDate + " 23:59:59");
            } else {
                totalOrders = consumptionRecordMapper.selectTodayTotalCount();
            }
            
            // 9. 统计购买记录数量
            long totalPurchases = 0;
            try {
                // 这里需要在PurchaseRecordMapper中添加相应的方法
                // totalPurchases = purchaseRecordMapper.selectTotalCountByDateRange(startDate + " 00:00:00", endDate + " 23:59:59");
            } catch (Exception e) {
                log.warn("查询购买记录数量失败: {}", e.getMessage());
            }
            
            // 10. 统计充值记录数量
            long totalRecharges;
            if (startDate != null && endDate != null) {
                totalRecharges = rechargeRecordMapper.selectTotalCountByDateRange(startDate + " 00:00:00", endDate + " 23:59:59");
            } else {
                totalRecharges = rechargeRecordMapper.selectTodayTotalCount();
            }
            
            // 11. 组装统计数据
            statistics.put("totalRevenue", totalRevenue);
            statistics.put("packageRevenue", packageRevenue != null ? packageRevenue : BigDecimal.ZERO);
            statistics.put("purchaseRevenue", purchaseRevenue != null ? purchaseRevenue : BigDecimal.ZERO);
            statistics.put("rechargeRevenue", rechargeRevenue != null ? rechargeRevenue : BigDecimal.ZERO);
            statistics.put("totalCost", totalCost);
            statistics.put("packageCost", packageCost);
            statistics.put("purchaseCost", purchaseCost);
            statistics.put("rechargeCost", rechargeCost);
            statistics.put("totalProfit", totalProfit);
            statistics.put("profitMargin", profitMargin);
            statistics.put("totalOrders", totalOrders);
            statistics.put("totalPurchases", totalPurchases);
            statistics.put("totalRecharges", totalRecharges);
            statistics.put("totalTransactions", totalOrders + totalPurchases + totalRecharges);
            
        } catch (Exception e) {
            log.error("获取平台统计数据失败", e);
            // 如果出错，返回零值
            statistics.put("totalRevenue", BigDecimal.ZERO);
            statistics.put("packageRevenue", BigDecimal.ZERO);
            statistics.put("purchaseRevenue", BigDecimal.ZERO);
            statistics.put("rechargeRevenue", BigDecimal.ZERO);
            statistics.put("totalCost", BigDecimal.ZERO);
            statistics.put("packageCost", BigDecimal.ZERO);
            statistics.put("purchaseCost", BigDecimal.ZERO);
            statistics.put("rechargeCost", BigDecimal.ZERO);
            statistics.put("totalProfit", BigDecimal.ZERO);
            statistics.put("profitMargin", BigDecimal.ZERO);
            statistics.put("totalOrders", 0L);
            statistics.put("totalPurchases", 0L);
            statistics.put("totalRecharges", 0L);
            statistics.put("totalTransactions", 0L);
        }
        
        return statistics;
    }
    
    /**
     * 获取全平台收入趋势数据
     */
    private Map<String, Object> getPlatformRevenueData(String startDate, String endDate, String timeType) {
        Map<String, Object> revenueData = new HashMap<>();
        
        try {
            // 根据时间类型生成日期列表
            List<String> dates = generateDateList(timeType);
            List<BigDecimal> revenueValues = new ArrayList<>();
            List<BigDecimal> costValues = new ArrayList<>();
            List<BigDecimal> profitValues = new ArrayList<>();
            
            LocalDate today = LocalDate.now();
            BigDecimal packageCostRate = new BigDecimal("0.20"); // 套餐成本率
            BigDecimal purchaseCostRate = new BigDecimal("0.60"); // 购物成本率
            
            for (String dateStr : dates) {
                // 查询该日期的收入数据
                String dayStart = dateStr + " 00:00:00";
                String dayEnd = dateStr + " 23:59:59";
                
                // 套餐收入（全平台）
                BigDecimal dayPackageRevenue = consumptionRecordMapper.selectTotalConsumeByDateRange(dayStart, dayEnd);
                
                // 购物收入（全平台）
                BigDecimal dayPurchaseRevenue = purchaseRecordMapper.selectTotalPurchaseIncomeByDateRange(dayStart, dayEnd);
                
                // 充值收入（全平台）
                BigDecimal dayRechargeRevenue = rechargeRecordMapper.selectTotalRechargeByDateRange(dayStart, dayEnd);
                
                // 总收入
                BigDecimal dayTotalRevenue = (dayPackageRevenue != null ? dayPackageRevenue : BigDecimal.ZERO)
                        .add(dayPurchaseRevenue != null ? dayPurchaseRevenue : BigDecimal.ZERO)
                        .add(dayRechargeRevenue != null ? dayRechargeRevenue : BigDecimal.ZERO);
                
                // 总成本（套餐成本 + 购物成本 + 充值成本）
                BigDecimal dayPackageCost = (dayPackageRevenue != null ? dayPackageRevenue : BigDecimal.ZERO)
                        .multiply(packageCostRate);
                BigDecimal dayPurchaseCost = (dayPurchaseRevenue != null ? dayPurchaseRevenue : BigDecimal.ZERO)
                        .multiply(purchaseCostRate);
                BigDecimal dayRechargeCost = (dayRechargeRevenue != null ? dayRechargeRevenue : BigDecimal.ZERO)
                        .multiply(new BigDecimal("0.02")); // 充值成本率2%
                BigDecimal dayTotalCost = dayPackageCost.add(dayPurchaseCost).add(dayRechargeCost);
                
                // 总利润
                BigDecimal dayTotalProfit = dayTotalRevenue.subtract(dayTotalCost);
                
                revenueValues.add(dayTotalRevenue);
                costValues.add(dayTotalCost);
                profitValues.add(dayTotalProfit);
            }
            
            revenueData.put("dates", dates);
            revenueData.put("revenueValues", revenueValues);
            revenueData.put("costValues", costValues);
            revenueData.put("profitValues", profitValues);
            
        } catch (Exception e) {
            log.error("获取平台收入趋势数据失败", e);
            revenueData.put("dates", new ArrayList<>());
            revenueData.put("revenueValues", new ArrayList<>());
            revenueData.put("costValues", new ArrayList<>());
            revenueData.put("profitValues", new ArrayList<>());
        }
        
        return revenueData;
    }
    
    /**
     * 获取成本分析数据
     */
    private Map<String, Object> getCostAnalysisData(String startDate, String endDate) {
        Map<String, Object> costData = new HashMap<>();
        
        try {
            // 获取购物收入
            BigDecimal purchaseRevenue;
            if (startDate != null && endDate != null) {
                purchaseRevenue = purchaseRecordMapper.selectTotalPurchaseIncomeByDateRange(startDate + " 00:00:00", endDate + " 23:59:59");
            } else {
                purchaseRevenue = purchaseRecordMapper.selectTodayTotalPurchaseIncome();
            }
            
            // 计算购物成本（假设成本率为60%）
            BigDecimal purchaseCostRate = new BigDecimal("0.60");
            BigDecimal purchaseCost = (purchaseRevenue != null ? purchaseRevenue : BigDecimal.ZERO)
                    .multiply(purchaseCostRate);
            
            // 套餐服务成本（主要是人工成本，假设为套餐收入的20%）
            BigDecimal packageRevenue;
            if (startDate != null && endDate != null) {
                packageRevenue = consumptionRecordMapper.selectTotalConsumeByDateRange(startDate + " 00:00:00", endDate + " 23:59:59");
            } else {
                packageRevenue = consumptionRecordMapper.selectTodayTotalConsume();
            }
            
            BigDecimal packageCostRate = new BigDecimal("0.20");
            BigDecimal packageCost = (packageRevenue != null ? packageRevenue : BigDecimal.ZERO)
                    .multiply(packageCostRate);
            
            // 充值成本（充值业务成本很低，假设为充值收入的2%）
            BigDecimal rechargeRevenue;
            if (startDate != null && endDate != null) {
                rechargeRevenue = rechargeRecordMapper.selectTotalRechargeByDateRange(startDate + " 00:00:00", endDate + " 23:59:59");
            } else {
                rechargeRevenue = rechargeRecordMapper.selectTodayTotalRecharge();
            }
            
            BigDecimal rechargeCostRate = new BigDecimal("0.02");
            BigDecimal rechargeCost = (rechargeRevenue != null ? rechargeRevenue : BigDecimal.ZERO)
                    .multiply(rechargeCostRate);
            
            BigDecimal totalCost = purchaseCost.add(packageCost).add(rechargeCost);
            
            costData.put("purchaseCost", purchaseCost);
            costData.put("packageCost", packageCost);
            costData.put("rechargeCost", rechargeCost);
            costData.put("totalCost", totalCost);
            
            // 成本占比
            if (totalCost.compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal purchaseCostRatio = purchaseCost.divide(totalCost, 4, RoundingMode.HALF_UP).multiply(new BigDecimal("100"));
                BigDecimal packageCostRatio = packageCost.divide(totalCost, 4, RoundingMode.HALF_UP).multiply(new BigDecimal("100"));
                BigDecimal rechargeCostRatio = rechargeCost.divide(totalCost, 4, RoundingMode.HALF_UP).multiply(new BigDecimal("100"));
                
                costData.put("purchaseCostRatio", purchaseCostRatio);
                costData.put("packageCostRatio", packageCostRatio);
                costData.put("rechargeCostRatio", rechargeCostRatio);
            } else {
                costData.put("purchaseCostRatio", BigDecimal.ZERO);
                costData.put("packageCostRatio", BigDecimal.ZERO);
                costData.put("rechargeCostRatio", BigDecimal.ZERO);
            }
            
        } catch (Exception e) {
            log.error("获取成本分析数据失败", e);
            costData.put("purchaseCost", BigDecimal.ZERO);
            costData.put("packageCost", BigDecimal.ZERO);
            costData.put("rechargeCost", BigDecimal.ZERO);
            costData.put("totalCost", BigDecimal.ZERO);
            costData.put("purchaseCostRatio", BigDecimal.ZERO);
            costData.put("packageCostRatio", BigDecimal.ZERO);
            costData.put("rechargeCostRatio", BigDecimal.ZERO);
        }
        
        return costData;
    }
    
    /**
     * 获取利润分析数据
     */
    private Map<String, Object> getProfitAnalysisData(String startDate, String endDate) {
        Map<String, Object> profitData = new HashMap<>();
        
        try {
            // 获取统计数据来计算利润
            Map<String, Object> statistics = getPlatformStatisticsData(startDate, endDate);
            
            BigDecimal totalRevenue = (BigDecimal) statistics.get("totalRevenue");
            BigDecimal totalCost = (BigDecimal) statistics.get("totalCost");
            BigDecimal totalProfit = (BigDecimal) statistics.get("totalProfit");
            BigDecimal profitMargin = (BigDecimal) statistics.get("profitMargin");
            
            profitData.put("totalRevenue", totalRevenue);
            profitData.put("totalCost", totalCost);
            profitData.put("totalProfit", totalProfit);
            profitData.put("profitMargin", profitMargin);
            
            // 各业务线利润分析
            BigDecimal packageRevenue = (BigDecimal) statistics.get("packageRevenue");
            BigDecimal purchaseRevenue = (BigDecimal) statistics.get("purchaseRevenue");
            BigDecimal rechargeRevenue = (BigDecimal) statistics.get("rechargeRevenue");
            
            // 套餐业务利润（利润率80%）
            BigDecimal packageCostRate = new BigDecimal("0.20");
            BigDecimal packageCost = packageRevenue.multiply(packageCostRate);
            BigDecimal packageProfit = packageRevenue.subtract(packageCost);
            BigDecimal packageProfitMargin = new BigDecimal("80");
            
            // 购物业务利润（利润率40%）
            BigDecimal purchaseCostRate = new BigDecimal("0.60");
            BigDecimal purchaseCost = purchaseRevenue.multiply(purchaseCostRate);
            BigDecimal purchaseProfit = purchaseRevenue.subtract(purchaseCost);
            BigDecimal purchaseProfitMargin = new BigDecimal("40");
            
            // 充值业务利润（利润率98%）
            BigDecimal rechargeCostRate = new BigDecimal("0.02");
            BigDecimal rechargeCost = rechargeRevenue.multiply(rechargeCostRate);
            BigDecimal rechargeProfit = rechargeRevenue.subtract(rechargeCost);
            BigDecimal rechargeProfitMargin = new BigDecimal("98");
            
            profitData.put("packageProfit", packageProfit);
            profitData.put("packageProfitMargin", packageProfitMargin);
            profitData.put("purchaseProfit", purchaseProfit);
            profitData.put("purchaseProfitMargin", purchaseProfitMargin);
            profitData.put("rechargeProfit", rechargeProfit);
            profitData.put("rechargeProfitMargin", rechargeProfitMargin);
            
        } catch (Exception e) {
            log.error("获取利润分析数据失败", e);
            profitData.put("totalRevenue", BigDecimal.ZERO);
            profitData.put("totalCost", BigDecimal.ZERO);
            profitData.put("totalProfit", BigDecimal.ZERO);
            profitData.put("profitMargin", BigDecimal.ZERO);
            profitData.put("packageProfit", BigDecimal.ZERO);
            profitData.put("packageProfitMargin", BigDecimal.ZERO);
            profitData.put("purchaseProfit", BigDecimal.ZERO);
            profitData.put("purchaseProfitMargin", BigDecimal.ZERO);
            profitData.put("rechargeProfit", BigDecimal.ZERO);
            profitData.put("rechargeProfitMargin", BigDecimal.ZERO);
        }
        
        return profitData;
    }
    

    
    /**
     * 生成日期列表
     */
    private List<String> generateDateList(String timeType) {
        List<String> dates = new ArrayList<>();
        LocalDate today = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        
        switch (timeType) {
            case "week":
                for (int i = 6; i >= 0; i--) {
                    dates.add(today.minusDays(i).format(formatter));
                }
                break;
            case "month":
                for (int i = 29; i >= 0; i--) {
                    dates.add(today.minusDays(i).format(formatter));
                }
                break;
            case "quarter":
                for (int i = 89; i >= 0; i -= 7) {
                    dates.add(today.minusDays(i).format(formatter));
                }
                break;
            default:
                // 默认30天
                for (int i = 29; i >= 0; i--) {
                    dates.add(today.minusDays(i).format(formatter));
                }
                break;
        }
        
        return dates;
    }
    
    @Override
    public Result<Map<String, Object>> getAdminSummaryReports(String startDate, String endDate) {
        try {
            Map<String, Object> result = new HashMap<>();
            
            if (startDate != null && endDate != null) {
                // 查询指定日期范围的汇总数据
                LocalDate start = LocalDate.parse(startDate);
                LocalDate end = LocalDate.parse(endDate);
                List<AdminReports> reports = adminReportsMapper.selectByDateRange(start, end);
                
                if (reports.isEmpty()) {
                    // 如果没有报表数据，从原始数据计算
                    Map<String, Object> statistics = getPlatformStatisticsData(startDate, endDate);
                    result.put("summary", statistics);
                    result.put("reports", new ArrayList<>());
                    result.put("message", "暂无报表数据，显示实时统计");
                } else {
                    // 计算汇总数据
                    BigDecimal totalRevenue = reports.stream()
                            .map(AdminReports::getTotalRevenue)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    
                    BigDecimal totalCost = reports.stream()
                            .map(AdminReports::getTotalCost)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    
                    BigDecimal totalProfit = reports.stream()
                            .map(AdminReports::getTotalProfit)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    
                    Integer totalOrders = reports.stream()
                            .map(AdminReports::getTotalOrders)
                            .reduce(0, Integer::sum);
                    
                    // 计算平均利润率
                    BigDecimal avgProfitMargin = BigDecimal.ZERO;
                    if (totalRevenue.compareTo(BigDecimal.ZERO) > 0) {
                        avgProfitMargin = totalProfit.divide(totalRevenue, 4, RoundingMode.HALF_UP)
                                .multiply(new BigDecimal("100"));
                    }
                    
                    Map<String, Object> summary = new HashMap<>();
                    summary.put("totalRevenue", totalRevenue);
                    summary.put("totalCost", totalCost);
                    summary.put("totalProfit", totalProfit);
                    summary.put("avgProfitMargin", avgProfitMargin);
                    summary.put("totalOrders", totalOrders);
                    summary.put("reportCount", reports.size());
                    
                    result.put("summary", summary);
                    result.put("reports", reports);
                }
            } else {
                // 获取最新的报表数据
                AdminReports latestReport = adminReportsMapper.selectLatest();
                if (latestReport != null) {
                    result.put("latestReport", latestReport);
                    result.put("reportDate", latestReport.getReportDate());
                } else {
                    // 如果没有报表数据，从原始数据计算今日统计
                    Map<String, Object> todayStatistics = getPlatformStatisticsData(null, null);
                    result.put("todayStatistics", todayStatistics);
                    result.put("message", "暂无报表数据，显示今日实时统计");
                }
            }
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取管理员总数据报表失败", e);
            return Result.error("获取管理员总数据报表失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result<String> generateAdminReports(String reportDate) {
        try {
            LocalDate targetDate = reportDate != null ? 
                    LocalDate.parse(reportDate) : LocalDate.now();
            
            log.info("开始生成管理员总数据报表，日期：{}", targetDate);
            
            // 计算指定日期的收入数据
            String dateStart = targetDate + " 00:00:00";
            String dateEnd = targetDate + " 23:59:59";
            
            // 1. 套餐收入
            BigDecimal packageRevenue = consumptionRecordMapper.selectTotalConsumeByDateRange(dateStart, dateEnd);
            
            // 2. 购物收入  
            BigDecimal purchaseRevenue = purchaseRecordMapper.selectTotalPurchaseIncomeByDateRange(dateStart, dateEnd);
            
            // 3. 充值收入
            BigDecimal rechargeRevenue = rechargeRecordMapper.selectTotalRechargeByDateRange(dateStart, dateEnd);
            
            // 4. 销售收入（目前为0）
            BigDecimal salesRevenue = BigDecimal.ZERO;
            
            // 5. 计算总收入
            BigDecimal totalRevenue = (packageRevenue != null ? packageRevenue : BigDecimal.ZERO)
                    .add(purchaseRevenue != null ? purchaseRevenue : BigDecimal.ZERO)
                    .add(rechargeRevenue != null ? rechargeRevenue : BigDecimal.ZERO)
                    .add(salesRevenue);
            
            // 6. 计算总成本
            BigDecimal packageCost = (packageRevenue != null ? packageRevenue : BigDecimal.ZERO)
                    .multiply(new BigDecimal("0.20"));
            BigDecimal purchaseCost = (purchaseRevenue != null ? purchaseRevenue : BigDecimal.ZERO)
                    .multiply(new BigDecimal("0.60"));
            BigDecimal rechargeCost = (rechargeRevenue != null ? rechargeRevenue : BigDecimal.ZERO)
                    .multiply(new BigDecimal("0.02"));
            BigDecimal salesCost = salesRevenue.multiply(new BigDecimal("0.40"));
            
            BigDecimal totalCost = packageCost.add(purchaseCost).add(rechargeCost).add(salesCost);
            
            // 7. 计算总利润
            BigDecimal totalProfit = totalRevenue.subtract(totalCost);
            
            // 8. 计算利润率
            BigDecimal profitMargin = BigDecimal.ZERO;
            if (totalRevenue.compareTo(BigDecimal.ZERO) > 0) {
                profitMargin = totalProfit.divide(totalRevenue, 4, RoundingMode.HALF_UP)
                        .multiply(new BigDecimal("100"));
            }
            
            // 9. 统计订单数量
            int packageOrders = 0;
            int purchaseOrders = 0; 
            int rechargeOrders = 0;
            int salesOrders = 0;
            
            try {
                packageOrders = Math.toIntExact(consumptionRecordMapper.selectTotalCountByDateRange(dateStart, dateEnd));
            } catch (Exception e) {
                log.warn("查询套餐订单数量失败: {}", e.getMessage());
            }
            
            try {
                rechargeOrders = Math.toIntExact(rechargeRecordMapper.selectTotalCountByDateRange(dateStart, dateEnd));
            } catch (Exception e) {
                log.warn("查询充值订单数量失败: {}", e.getMessage());
            }
            
            int totalOrders = packageOrders + purchaseOrders + rechargeOrders + salesOrders;
            
            // 10. 创建AdminReports对象
            AdminReports adminReports = new AdminReports();
            adminReports.setReportDate(targetDate);
            adminReports.setPackageRevenue(packageRevenue != null ? packageRevenue : BigDecimal.ZERO);
            adminReports.setPurchaseRevenue(purchaseRevenue != null ? purchaseRevenue : BigDecimal.ZERO);
            adminReports.setRechargeRevenue(rechargeRevenue != null ? rechargeRevenue : BigDecimal.ZERO);
            adminReports.setSalesRevenue(salesRevenue);
            adminReports.setTotalRevenue(totalRevenue);
            adminReports.setTotalCost(totalCost);
            adminReports.setTotalProfit(totalProfit);
            adminReports.setProfitMargin(profitMargin);
            adminReports.setTotalOrders(totalOrders);
            adminReports.setTotalTransactions(totalOrders);
            
            // 11. 插入或更新数据
            int result = adminReportsMapper.insertOrUpdate(adminReports);
            
            if (result > 0) {
                String message = String.format("管理员总数据报表生成成功！日期：%s，总收入：￥%s，总利润：￥%s", 
                        targetDate, totalRevenue, totalProfit);
                log.info(message);
                return Result.success(message);
            } else {
                return Result.error("管理员总数据报表生成失败");
            }
            
        } catch (Exception e) {
            log.error("生成管理员总数据报表失败", e);
            return Result.error("生成管理员总数据报表失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result<Map<String, Object>> getAdminReportsHistory(String startDate, String endDate, int page, int size) {
        try {
            Map<String, Object> result = new HashMap<>();
            
            LocalDate start = startDate != null ? LocalDate.parse(startDate) : LocalDate.now().minusMonths(3);
            LocalDate end = endDate != null ? LocalDate.parse(endDate) : LocalDate.now();
            
            // 查询历史报表数据
            List<AdminReports> allReports = adminReportsMapper.selectByDateRange(start, end);
            
            // 手动分页
            int total = allReports.size();
            int offset = (page - 1) * size;
            int toIndex = Math.min(offset + size, total);
            
            List<AdminReports> pageReports = new ArrayList<>();
            if (offset < total) {
                pageReports = allReports.subList(offset, toIndex);
            }
            
            // 计算汇总统计
            BigDecimal totalRevenue = allReports.stream()
                    .map(AdminReports::getTotalRevenue)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            
            BigDecimal totalProfit = allReports.stream()
                    .map(AdminReports::getTotalProfit)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            
            Integer totalOrders = allReports.stream()
                    .map(AdminReports::getTotalOrders)
                    .reduce(0, Integer::sum);
            
            Map<String, Object> summary = new HashMap<>();
            summary.put("totalRevenue", totalRevenue);
            summary.put("totalProfit", totalProfit);
            summary.put("totalOrders", totalOrders);
            summary.put("reportDays", total);
            
            result.put("reports", pageReports);
            result.put("summary", summary);
            result.put("total", total);
            result.put("page", page);
            result.put("size", size);
            result.put("totalPages", (int) Math.ceil((double) total / size));
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取管理员报表历史数据失败", e);
            return Result.error("获取管理员报表历史数据失败：" + e.getMessage());
        }
    }
} 